import React, {Component} from 'react';
import {connect} from 'dva';
import styles from "./Dept.less";
import {Layout} from "antd";
import {Tabs} from "antd";
import {Descriptions} from "antd";
import {Table} from "antd";
import {Button} from "antd";
import {PageHeader} from "antd";
import {Breadcrumb} from "antd";
import {Input} from "antd";
import {ConnectState} from "@/models/connect";
import {handleTree} from "@/utils/utils";
import {updateState} from "@/utils/utils";
import {exeRequestResult} from "@/utils/utils";
import {get} from "lodash"
import OaTree from "@/pages/Public/OaTree/OaTree";
import {Observable} from "rxjs";
import {orgDeptAncestors} from "@/services/api";
import {orgDept} from "@/services/api";
import {getEmployee} from "@/services/api";
import {saveOrgDept} from "@/services/api";
import defaultSet from "@/services/defaultSet";
import {BarsOutlined} from "@ant-design/icons/lib";
import {ApartmentOutlined} from "@ant-design/icons/lib";
import {TeamOutlined} from "@ant-design/icons/lib";
import {FileSearchOutlined} from "@ant-design/icons/lib";
import {EditOutlined} from "@ant-design/icons/lib";
import {HomeOutlined} from "@ant-design/icons/lib";
import {CompassOutlined} from "@ant-design/icons/lib";
import {CheckOutlined} from "@ant-design/icons/lib";
import {CloseOutlined} from "@ant-design/icons/lib";
import OaUser from "@/pages/Public/OaUser/OaUser";
import OaGrade from "@/pages/Public/OaGrade/OaGrade";
import OaStatusSwitch from "@/pages/Public/OaStatusSwitch/OaStatusSwitch";
import {DeptParams} from "@/pages/Public/Public.interface";
import {Row} from "antd";
import {Col} from "antd";
import {Card} from "antd";
const {Sider, Header, Content} = Layout;
const {TabPane} = Tabs;
class Dept extends Component {
  state = {
    nodeId: "",
    pageNum: 1,
    pageSize: 100,
    searchValue: "",
    listDept: [],
    ancestors: {},
    employee: {},
    orgDept: {},
    orgDeptPagination: defaultSet.PAGINATION,
    employeePagination: defaultSet.PAGINATION,
    editState: {
      orgDept: false
    },
    deptParams: {} as DeptParams
  };
  componentDidMount() {
    let employeePagination = this.state.employeePagination
    employeePagination["total"] = 1
    this.setState({
      employeePagination
    })
    this.fetchListDept().subscribe((res: any) => {
      let firstId = get(this.state.listDept[0], "key", "")
      this.init(1, firstId)
    })
  }
  init = (current: any, id: any) => {
    this.setState({
      nodeId: id
    })
    //初始化展示第一个
    //获取上级部门
    this.fetchOrgDeptAncestors(id)
    this.fetchOrgDept(id)
    this.fetchGetEmployee(current, id)
  }
  async fetchGetEmployee(current: number, deptId: string) {
    let params = {
      pageSize: this.state.employeePagination.pageSize,
      pageNum: this.state.employeePagination.current,
      total: this.state.employeePagination.total,
      deptId: deptId
    }
    let result = await getEmployee(params)
    let pagination = this.state.employeePagination
    pagination.total = get(result, "total", 1)
    pagination.current = current
    pagination.onChange = (res: any) => {
      let _pagination = this.state.employeePagination
      _pagination.current = res
      this.setState({
        employeePagination: _pagination
      }, (res: any) => {
        this.fetchGetEmployee(current, deptId)
      })
    }
    pagination.onShowSizeChange = (current: any, size: any) => {
      let _pagination = this.state.employeePagination
      _pagination.pageSize = size
      this.setState({
        employeePagination: _pagination
      }, (res: any) => {
        this.fetchGetEmployee(res, deptId)
      })
    }
    this.setState({
      employee: result,
      employeePagination: pagination
    })
  }
  //获取上级部门
  async fetchOrgDeptAncestors(id: string = "") {
    let result = await orgDeptAncestors(id)
    this.setState({
      ancestors: result
    })
  }
  async fetchOrgDept(id: string = "") {
    let result = await orgDept(id)
    let data = get(result, "data", {})
    this.setState({
      orgDept: data,
      deptParams: data
    })
  }
  fetchListDept() {
    return new Observable(ob => {
      this.props.dispatch({
        type: "global/fetchListDept"
      }).then((res: any) => {
        let data = get(this.props, "listDept", {}).data
        //设置树形数据
        let listDept = handleTree(data, 'id', 'parentId', 'children', 1)
        this.setState({
          listDept
        }, (res: any): Promise<void> => {
          ob.next()
          ob.complete()
        })
      })
    })
  }
  selectNode = (selectedKeys, {selected, selectedNodes, node, event}) => {
    this.init(1, selectedKeys)
    let editState = this.state.editState
    editState.orgDept = false
    this.setState({
      editState
    })
  }
  //编辑状态改变
  editStateChange = (res: any) => {
    let editState = this.state.editState
    this.state.editState.orgDept = res
    this.setState({
      editState
    })
    if (!res) {
      this.init(1, this.state.nodeId)
    }
  }
  //部门名字
  deptNameChange = (res: any) => {
    let value = res.currentTarget.value
    updateState(this, "deptParams", "deptName", value, (res: any) => {
    })
  }
  //负责人
  OaUserOnChange = (getarr: any) => {
    updateState(this, "deptParams", "leader", getarr, (res: any) => {
    })
  }
  //级别
  OaGradeOnChange = (res: any) => {
    updateState(this, "deptParams", "grade", res, (res: any) => {
    })
  }
  //状态
  OaStatusSwitchOnChange = (res: any) => {
    updateState(this, "deptParams", "status", res, (res: any) => {
    })
  }
  editSubmit = () => {
    if (this.state.editState.orgDept == false) {
      this.editStateChange(true)
    } else {
      let params = this.state.deptParams
      saveOrgDept(params).then((res: any) => {
        let bool = exeRequestResult(res)
        if (bool) {
          this.editStateChange(false)
        }
      })
    }
  }
  render() {
    return <>

      <div className={styles.Dept}>

        <PageHeader style={{background: "#fff", marginBottom: 12}} title={
          <>
            <div><Breadcrumb separator=">">
              {get(this.state.ancestors, "data", []).map((res: any, index: any) => {
                return <Breadcrumb.Item key={index}> {index == 0 ? <HomeOutlined/> :
                  <CompassOutlined/>} {get(res, "deptName", "")}</Breadcrumb.Item>
              })}
            </Breadcrumb></div>
          </>
        }></PageHeader>

        <Row gutter={12}>
          <Col  span={6}>
            <Card className={'oaCard'} bordered={false} title={false}>
              <OaTree onSelect={this.selectNode} treeData={this.state.listDept}/>
            </Card>
          </Col>
          <Col span={18}>
            <Card className={'oaCard'}  bordered={false} title={false}>
              <Tabs defaultActiveKey="1">
                {/*---部门信息---*/}
                <TabPane
                  tab={
                    <span>
          <BarsOutlined/>
          部门信息
        </span>
                  }
                  key="1"
                >
                  <Descriptions key={"部门"} column={2} bordered size={'default'} title={false}>
                    {/*部门名字*/}
                    <Descriptions.Item label="部门名称" key="部门名称">
                      {this.state.editState.orgDept ?
                        <Input onChange={this.deptNameChange} defaultValue={get(this.state.orgDept, "deptName", "")}/>
                        : get(this.state.orgDept, "deptName", " ")}
                    </Descriptions.Item>
                    {/*负责人*/}
                    <Descriptions.Item label="负责人" key="负责人">
                      {this.state.editState.orgDept ?
                        <OaUser currentValue={get(this.state.orgDept, "leader", " ")} onChange={this.OaUserOnChange}/>
                        : get(this.state.orgDept, "leader", " ")}
                    </Descriptions.Item>
                    {/*部门级别*/}
                    <Descriptions.Item label="部门级别" key="部门级别">{this.state.editState.orgDept ?
                      <OaGrade onChange={this.OaGradeOnChange}
                               currentValue={get(this.state.orgDept, "grade", " ")}/> : get(this.state.orgDept, "grade", " ")}</Descriptions.Item>
                    {/*状态*/}
                    <Descriptions.Item
                      key="状态" label="状态">
                      {this.state.editState.orgDept ? <OaStatusSwitch
                        onChange={this.OaStatusSwitchOnChange}
                        currentValue={this.state.orgDept.status}/> : get(this.state.orgDept, "status", 0) == 0 ? "关闭" : "正常"}
                    </Descriptions.Item>
                  </Descriptions>
                  {/*编辑*/}
                  <div style={{
                    marginTop: 24,
                    display: "flex",
                    alignItems: "center",
                    width: "100%",
                    justifyContent: "center",
                    flexDirection: "row"
                  }}>
                    <Button onClick={() => {
                      this.editSubmit()
                    }} type={"primary"}
                            icon={this.state.editState.orgDept ? <CheckOutlined/> : <EditOutlined/>}>
                      {
                        this.state.editState.orgDept ? "提交" : "编辑"
                      }
                    </Button>
                    {
                      this.state.editState.orgDept &&
                      <>
                          &nbsp;&nbsp;&nbsp;&nbsp;<Button onClick={() => {
                        this.editStateChange(false)
                      }} type={"default"}
                                                          icon={<CloseOutlined/>}>
                          取消
                      </Button>
                      </>
                    }
                  </div>
                </TabPane>
                {/*---部门成员---*/}
                <TabPane
                  tab={
                    <span>
          <ApartmentOutlined/>
          部门成员
        </span>
                  }
                  key="2"
                >
                  <Table pagination={this.state.employeePagination} style={{width: "100%"}} columns={[
                    {
                      key: "userName",
                      dataIndex: "userName",
                      title: "用户名"
                    },
                    {
                      key: "deptName",
                      dataIndex: "deptName",
                      title: "部门"
                    }, {
                      key: "deptName2",
                      dataIndex: "deptName",
                      title: "职位"
                    }, {
                      key: "entryTime",
                      dataIndex: "entryTime",
                      title: "入职时间"
                    }, {
                      key: "deptName3",
                      dataIndex: "deptName",
                      title: "部门"
                    }, {
                      key: "phone",
                      dataIndex: "phone",
                      title: "手机"
                    },
                    {
                      key: "detail",
                      dataIndex: "detail",
                      title: "详情",
                      render: (res: any) => {
                        return <Button type={"primary"} icon={<FileSearchOutlined/>}>查看</Button>
                      }
                    },
                  ]} dataSource={get(this.state.employee, "rows", [])}/>
                </TabPane>
                {/*---管理人员---*/}
                <TabPane
                  tab={
                    <span>
          <TeamOutlined/>
          管理人员
        </span>
                  }
                  key="3"
                >
                  <Table pagination={this.state.employeePagination} style={{width: "100%"}} columns={[
                    {
                      key: "userName",
                      dataIndex: "userName",
                      title: "姓名"
                    },
                    {
                      key: "deptName2",
                      dataIndex: "deptName",
                      title: "部门"
                    }, {
                      key: "deptName3",
                      dataIndex: "deptName",
                      title: "职位"
                    }, {
                      key: "eleadEmail",
                      dataIndex: "eleadEmail",
                      title: "企业邮箱"
                    },
                  ]} dataSource={get(this.state.orgDept, "adminGroup", [])}/>
                </TabPane>
              </Tabs>
            </Card>
          </Col>
        </Row>
      </div>
    </>
  }
}
export default connect(
  ({global}: ConnectState) => ({
    employee: global.employee,
    listDept: global.listDept
  }),
)(Dept);
